package org.ouwh.fw.timer;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ouwh.fw.model.data.Struct;
import org.ouwh.fw.model.service.Service;

public class TimerService extends Service {
	private static final String INTERVAL = "interval";

	private static final String TASK_CLASS = "task-class";

	private static Log log = LogFactory.getLog(TimerService.class);

	private TimerThread timerThread;

	private String taskClassName;

	private long interval = 60000;

	@Override
	protected void init(Properties props) {
		taskClassName = props.getProperty(TASK_CLASS);
		interval = Long.parseLong(props.getProperty(INTERVAL));
		log.info("TimerService[" + getId() + "]initialized.");
	}

	@Override
	protected void startup() throws Exception {
		ITimerTask task = (ITimerTask) Class.forName(taskClassName).newInstance();
		timerThread = new TimerThread();
		timerThread.setTask(task);
		timerThread.setInterval(interval);
		timerThread.setName(getId());
		timerThread.startup();
		log.info("TimerService[" + getId() + "]started.");
	}

	@Override
	protected void reset(Properties props) throws Exception {
		String tmpTaskClass = props.getProperty(TASK_CLASS);
		interval = Long.parseLong(props.getProperty(INTERVAL));
		if (tmpTaskClass.equals(taskClassName)) {
			timerThread.setInterval(interval);
			log.info("TimerService[" + getId() + "]resetted without restart.");
		} else {
			stop();
			start();
			log.info("TimerService[" + getId() + "]resetted by restart.");
		}
	}

	protected void shutdown() {
		log.info("TimerService[" + getId() + "]stopping...");
		timerThread.shutdown();
		log.info("TimerService[" + getId() + "]stopped.");
	}

	@Override
	protected void dumpToStruct(Struct struct) {
		struct.addData(TASK_CLASS, taskClassName);
		struct.addData(INTERVAL, timerThread.getInterval());
		struct.addData("task-info", timerThread.getTaskInfo());
	}
}
